import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/student/ProfileStudent.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/widgets/dialogs/addChildToParent.dart';
import 'package:ichinesereader/widgets/grids/parentChildrenDataGrid.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerParent.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/parentSidebar.dart';
import 'package:ichinesereader/widgets/sidebars/settingsBarHorizontal.dart';
import '../../themes/pageStyles.dart';

class ParentHome extends StatefulWidget {
  static const String routeName = '/parent/home';

  @override
  _ParentHomeState createState() => _ParentHomeState();
}

class _ParentHomeState extends State<ParentHome> {
  final UserController _userController = Get.find();
  final box = Hive.box('appconfig');

  @override
  void initState() {
    bool isParent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Parent;
    if (isParent) {
      Future.delayed(Duration(milliseconds: 200), (() {
        _userController.getProfile();
      }));
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('start building parent home page');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.parentPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final PageStyles _pageStyles = PageStyles();

    Log.debug(_userController.currentChild.value.userName);
    return Scaffold(
      appBar: isSmallScreen ? CustomAppBar(title: 'Home'.tr) : null,
      drawer: isSmallScreen ? ParentAppDrawer() : null,
      body: Container(
        decoration: _pageStyles.pageBoxDecoration(),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Visibility(
              visible: !isSmallScreen,
              child: ParentSidebarX(
                  selectedIndex: _selectedSidebarItem,
                  isBigScreen: isBigScreen),
            ),
            Expanded(
                child: Container(
              margin: _pageStyles.mainContainerPageEdgeInsets(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  /////Desktop Top Bar///////
                  Container(
                    margin: EdgeInsets.only(
                      right: 6.0,
                      bottom: 6.0,
                    ),
                    decoration: BoxDecoration(
                      color: Get.isDarkMode
                          ? Colors.white.withOpacity(0.1)
                          : Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(3),
                      boxShadow: [
                        BoxShadow(
                          blurRadius: 9,
                          spreadRadius: 1,
                          color: Get.isDarkMode
                              ? Colors.transparent
                              : Colors.black.withOpacity(0.1),
                          offset: Offset(3, 3),
                        ),
                      ],
                    ),
                    padding: EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 12,
                    ),
                    child: SettingsBarHorizontal(!isSmallScreen, 'Home'),
                  ),

                  //Student CHIPS///
                  Obx(() {
                    var filteredOptions = _userController.parentChildren.where(
                        (element) =>
                            element.classResps != null &&
                            element.classResps!.isNotEmpty);
                    return Visibility(
                        visible: filteredOptions.isNotEmpty,
                        child: Container(
                          margin: EdgeInsets.only(
                            right: 6.0,
                            bottom: 6.0,
                          ),
                          decoration: BoxDecoration(
                              color: Get.isDarkMode
                                  ? Colors.white.withOpacity(0.1)
                                  : Colors.white.withOpacity(0.3),
                              borderRadius: BorderRadius.circular(3.0)),
                          padding: EdgeInsets.symmetric(
                            horizontal: 21.0,
                          ),
                          child: filteredOptions.isNotEmpty
                              ? Row(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: FormBuilder(
                                        child: FormBuilderChoiceChip(
                                          decoration: InputDecoration(
                                            prefixIcon: Padding(
                                              padding:
                                                  const EdgeInsets.all(2.0),
                                              child: Tooltip(
                                                  message: 'Select Student'.tr,
                                                  child: Icon(Icons
                                                      .people_alt_rounded)),
                                            ),
                                            prefixIconColor: Get.isDarkMode
                                                ? Colors.black
                                                : Colors.white.withOpacity(0.8),
                                          ),
                                          spacing: 9.0,
                                          backgroundColor: Get.isDarkMode
                                              ? Get.theme.primaryColor
                                              : Colors.blueGrey,
                                          selectedColor: Get.isDarkMode
                                              ? Colors.white
                                              : Theme.of(context)
                                                  .primaryColorDark,
                                          initialValue: _userController
                                              .currentChild.value,
                                          name: 'parent_student_chip',
                                          onChanged: (value) {
                                            if (value == null) return;
                                            try {
                                              _userController.setCurrentChild(
                                                  value as ProfileStudent);
                                            } catch (error) {
                                              Log.debug(error);
                                            }
                                          },
                                          options: filteredOptions
                                              .map((student) =>
                                                  FormBuilderChipOption<
                                                      ProfileStudent>(
                                                    value: student,
                                                    child: Text(
                                                      '${student.firstName} ${student.lastName}'
                                                          .toString(),
                                                      style: TextStyle(
                                                        color: Get.isDarkMode
                                                            ? Colors.black
                                                            : Get.theme
                                                                .primaryColorLight,
                                                        fontSize: 16,
                                                        letterSpacing: 1,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ))
                                              .toList(),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      margin:
                                          EdgeInsets.symmetric(vertical: 6.0),
                                      child: Stack(
                                          alignment: Alignment.center,
                                          children: [
                                            Container(
                                              width: 39,
                                              height: 39,
                                              decoration: BoxDecoration(
                                                color: Get.isDarkMode
                                                    ? Colors.white
                                                        .withOpacity(0.3)
                                                    : Get
                                                        .theme.primaryColorLight
                                                        .withOpacity(0.3),
                                                borderRadius:
                                                    BorderRadius.circular(6),
                                                boxShadow: [
                                                  BoxShadow(
                                                    blurRadius: 6,
                                                    spreadRadius: 1,
                                                    color: Get.isDarkMode
                                                        ? Colors.transparent
                                                        : Colors.black
                                                            .withOpacity(0.1),
                                                    offset: Offset(3, 3),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            Container(
                                              width: 30,
                                              height: 30,
                                              decoration: BoxDecoration(
                                                color: Get.isDarkMode
                                                    ? Get.theme.primaryColorDark
                                                    : Get.theme.primaryColorDark
                                                        .withOpacity(0.3),
                                                borderRadius:
                                                    BorderRadius.circular(3),
                                              ),
                                            ),
                                            Container(
                                              child: Center(
                                                child: IconButton(
                                                  icon: const Icon(
                                                    Icons.add_circle,
                                                  ),
                                                  color: Get.isDarkMode
                                                      ? Colors.black
                                                      : Colors.white
                                                          .withOpacity(0.8),
                                                  onPressed: () {
                                                    showGeneralDialog(
                                                        context: context,
                                                        transitionDuration:
                                                            Duration(
                                                                milliseconds:
                                                                    0),
                                                        pageBuilder:
                                                            (bc, ania, anis) {
                                                          return AddChildToParent();
                                                        });
                                                  },
                                                ),
                                              ),
                                            ),
                                          ]),
                                    ),
                                  ],
                                )
                              : Text(''),
                        ));
                  }),
                  _userController.obx(
                    (data) => Expanded(
                        child: ParentChildrenDataGrid(
                            _userController.parentChildren)),
                    onEmpty: Expanded(
                        child: ParentChildrenDataGrid(
                            _userController.parentChildren)),
                  )
                ],
              ),
            ))
          ],
        ),
      ),
    );
  }
}
